package com.ruoyi.asset.common;

import com.itextpdf.io.font.PdfEncodings;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.TextAlignment;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.print.PrintService;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.Sides;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.PrinterJob;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author jiangxiangjin
 * @version V1.0.0
 * @description
 * @date 2023/4/17 16:57
 */
@Component
@Slf4j
public class PDFUtils {
    private static String address;

    @Value("${print.address}")
    public void setAddress(String address) {
        PDFUtils.address = address;
    }

    private static String printerName;

    @Value("${print.printerName}")
    public void setPrinterName(String printerName) {
        PDFUtils.printerName = printerName;
    }

    private static String fontAddress;

    @Value("${print.fontAddress}")
    public void setFontAddress(String fontAddress) {
        PDFUtils.fontAddress = fontAddress;
    }

    public static File createPDF(String filename, List<Map<String, String>> maps) {

        String outputFile = address + "/" + filename + ".pdf";

        File file = new File(address);
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
            // 创建 PdfWriter 对象
            PdfWriter writer = new PdfWriter(outputFile);


            // 创建 PdfDocument 对象
            PdfDocument pdf = new PdfDocument(writer);

            // 创建 Document 对象
            Document document = new Document(pdf, new PageSize(283.5f, 198.5f));
            PageSize pageSize = new PageSize(283.5f, 198.5f);
//            Document document = new Document(pdf);
            document.setMargins(0, 0, 0, 0);
            for (Map<String, String> map : maps) {
                pdf.addNewPage(pageSize);
                // 创建表格
                Table table = new Table(new float[]{80f, 203.f}); // 3 列的表格
                table.setWidth(283f);// 设置表格宽度占页面宽度的百分比
                table.setHeight(198f);
                table.setBorder(new SolidBorder(1f));


                // 使用SimSun字体（宋体）来显示中文
//            PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", true);
                PdfFont font =
                        PdfFontFactory.createFont(fontAddress + "wqy-zenhei.ttc,0", PdfEncodings.IDENTITY_H, true);

                // 合并第一行的两个单元格
                Cell mergedCell = new Cell(1, 2); // 跨1行、2列
                mergedCell.setBorder(new SolidBorder(1f));
                Paragraph paragraph = createParagraph(font, "固定资产标识卡");
                paragraph.setCharacterSpacing(20f);
                mergedCell.add(paragraph);
                table.addCell(mergedCell);

                List<String> list = new ArrayList<>();
                list.add("资产名称");
                list.add("资产编号");
                list.add("规格型号");
                list.add("使用部门");
                list.add("使用时间");
                list.add("使用人");


                for (String s : list) {
                    insertCellToTable(table, s, font, map.get(s));
                }


                document.add(table);
            }

            // 关闭 Document 对象
            document.close();

            log.debug("成功生成 PDF 文件：" + outputFile);
        } catch (FileNotFoundException e) {
            log.debug("文件未找到异常：" + e.getMessage());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return new File(outputFile);
    }

    private static void insertCellToTable(Table table, String text, PdfFont font, String key) throws IOException {
        Cell cell1 = new Cell();
        cell1.setBorder(new SolidBorder(1f));
        Paragraph paragraph = createParagraph(font, text);
        cell1.add(paragraph);
        table.addCell(cell1);

        Cell cell2 = new Cell();
        cell2.setBorder(new SolidBorder(1f));
        Paragraph paragraph2 = createParagraph(font, key);
        cell2.add(paragraph2);
        table.addCell(cell2);
    }


    public static Paragraph createParagraph(PdfFont font, String text) {
        Paragraph paragraph = new Paragraph(text);
        paragraph.setFont(font);
        paragraph.setTextAlignment(TextAlignment.CENTER);
        return paragraph;
    }


    public static void PDFprint(File file) throws Exception {
        PDDocument document = null;
        try {
            document = PDDocument.load(file);
            PrinterJob printJob = PrinterJob.getPrinterJob();
            printJob.setJobName(file.getName());
            if (printerName != null) {
                // 查找并设置打印机
                //获得本台电脑连接的所有打印机
                PrintService[] printServices = PrinterJob.lookupPrintServices();
                if (printServices == null || printServices.length == 0) {
                    log.debug("打印失败，未找到可用打印机，请检查。");
                    return;
                }
                PrintService printService = null;
                //匹配指定打印机
                for (int i = 0; i < printServices.length; i++) {
                    System.out.println(printServices[i].getName());
                    if (printServices[i].getName().contains(printerName)) {
                        printService = printServices[i];
                        break;
                    }
                }
                if (printService != null) {
                    printJob.setPrintService(printService);
                } else {
                    log.debug("打印失败，未找到名称为" + printerName + "的打印机，请检查。");
                    return;
                }
            }
            //设置纸张及缩放
            PDFPrintable pdfPrintable = new PDFPrintable(document, Scaling.ACTUAL_SIZE);

            //设置多页打印
            Book book = new Book();
            PageFormat pageFormat = new PageFormat();
            //设置打印方向
            pageFormat.setOrientation(PageFormat.PORTRAIT);//纵向
            pageFormat.setPaper(getPaper());//设置纸
            book.append(pdfPrintable, pageFormat, document.getNumberOfPages());
            printJob.setPageable(book);
            printJob.setCopies(1);//设置打印份数
            //添加打印属性
            HashPrintRequestAttributeSet pars = new HashPrintRequestAttributeSet();
            pars.add(Sides.DUPLEX); //设置单双页
            printJob.print(pars);
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Paper getPaper() {
        Paper paper = new Paper();
        // 默认为A4纸张，对应像素宽和高分别为 595, 842
        int width = 284;
        int height = 199;
        // 设置边距，单位是像素，10mm边距，对应 28px
        int marginLeft = 0;
        int marginRight = 0;
        int marginTop = 0;
        int marginBottom = 0;
        paper.setSize(width, height);
        // 下面一行代码，解决了打印内容为空的问题
        paper.setImageableArea(marginLeft, marginRight, width - (marginLeft + marginRight), height - (marginTop + marginBottom));
        return paper;
    }


//    public static byte[] convertPdfToBytes(File file) throws IOException {
//        // 读取PDF文件到PDDocument对象中
////        PDDocument document = PDDocument.load(file);
//
//        // 创建一个输出流，并将PDDocument对象写入到该流中
//        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        document.save(outputStream);
//        document.close();
//
//        // 返回字节数组
//        return outputStream.toByteArray();
//    }

}
